// 310.最小高度树

package Leetcode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Solution310 {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> result = new ArrayList<>();

        if (n == 1) {
            result.add(0);
            return result;
        }

        // 1. 建立每个节点的度表
        int[] degree = new int[n];

        // 2. 记录每个节点连接的其他节点
        List<List<Integer>> connection = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            connection.add(new ArrayList<>());
        }

        // 3. 遍历数组，获取对应值
        for (int[] edge : edges) {
            degree[edge[0]]++;
            degree[edge[1]]++;
            connection.get(edge[0]).add(edge[1]);
            connection.get(edge[1]).add(edge[0]);
        }

        // 4. 建立队列并加入所有的叶子节点
        Deque<Integer> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            if (degree[i] == 1)
                queue.offer(i);
        }

        while (!queue.isEmpty()) {
            result = new ArrayList<>();
            int size = queue.size();
            while (size-- != 0) {
                Integer poll = queue.poll();
                result.add(poll);

                List<Integer> neighbours = connection.get(poll);

                for (Integer neighbour : neighbours) {
                    if (--degree[neighbour] == 1)
                        queue.offer(neighbour);
                }
            }
        }

        return result;
    }

}
